﻿using System;
using System.Runtime.Serialization;
using ExFlash.Records;

namespace ExFlash.Tags
{
    public class DefineFontInfo2Tag : DefineFontInfoTag
    {
        
        public LangCode LanguageCode
        {
            get;
            protected set;
        }

        public DefineFontInfo2Tag(int len, int offset, IDictionaryIdQueryable querySource)
            : this(TagCodes.DefineFontInfo2, len, offset, querySource)
        {

        }

        protected DefineFontInfo2Tag(TagCodes code, int len, int offset, IDictionaryIdQueryable querySource)
            : base(code, len, offset, querySource)
        {

        }

        public override void SwfDeserialize(BinaryBitReader reader)
        {
            FontID = reader.ReadUInt16();

            FontNameLen = reader.ReadByte();

            FontName = new Byte[FontNameLen];
            reader.Read(FontName, 0, FontNameLen);

            // Reserved
            reader.SkipBits(2);

            FontFlagsSmallText = reader.ReadBoolean();
            FontFlagsShiftJIS = reader.ReadBoolean();
            FontFlagsANSI = reader.ReadBoolean();
            FontFlagsItalic = reader.ReadBoolean();
            FontFlagsBold = reader.ReadBoolean();
            FontFlagsWideCodes = reader.ReadBoolean();

            reader.AlignBits();

            LanguageCode = (LangCode)reader.ReadByte();

            Tag tag;
            DefineFontTag fontTag;

            if (QuerySource.TryGetValue(FontID, out tag) == false)
            {
                throw new SerializationException("DefineFontInfo Tag referring to unknown Font ID");
            }
            
            if ((fontTag = tag as DefineFontTag) == null)
            {
                throw new SerializationException("ID exists but doesn't belong to a font Tag");
            }

            CodeTable = new ushort[fontTag.NumGylphs];

            for (int i = 0; i < fontTag.NumGylphs; i++)
            {
                CodeTable[i] = reader.ReadUInt16();
            }
   
        }

        public override void SwfSerialize(byte[] arr, ref int offset)
        {
            throw new NotImplementedException();
        }
    }
}
